<template>
  <div class="container">
    <div class="app-container">
      <el-tree :expand-on-click-node="false" :data="depts" :props="defaultProps" default-expand-all>
        <!-- 布局组件 el-row-el-col -->
        <template v-slot="{ data }">
          <el-row style="width: 100%; height: 40px;" type="flex">
            <el-col>{{ data.name }}</el-col>
            <el-col>
              <el-row type="flex" justify="end">
                <span class="username">管理员</span>
                <el-dropdown @command="operateDept($event,data.id)">
                  <span class="username">操作<i class="el-icon-arrow-down" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                    <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                    <el-dropdown-item command="del">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <add-dept ref="addDept" :show-dialog.sync="showDialog" :current-node-id="currentNodeId" @updateDept="getDepartment" />
  </div>
</template>

<script>
import { delDepartMentAPI, getDepartmentAPI } from '@/api'
import { transListToTreeData } from '@/utils'
import AddDept from './components/add-dept.vue'
export default {
  name: 'Department',
  components: { AddDept },
  data() {
    return {
      currentNodeId: null,
      showDialog: false,
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      this.depts = transListToTreeData(await getDepartmentAPI(), 0)
    },
    async operateDept(type, id) {
      if (type === 'add') {
        this.showDialog = true
        this.currentNodeId = id
      } else if (type === 'edit') {
        this.currentNodeId = id
        await this.$refs.addDept.getDepartMentDetail(id)
        this.showDialog = true
      } else {
        await this.$confirm('确认删除该部门吗')
        await delDepartMentAPI(id)
        this.$message.success('删除部门成功')
        this.getDepartment()
      }
    }
  }
}
</script>

<style scoped>
  .app-container {
    padding: 20px 50px;
  }
  .username {
    margin-right: 10px;
    font-size: 14px;
  }
  .el-row{
    align-items: center;
  }
</style>

